//将文件读写相关的操作封装成promise

const fs = require('fs')
const path = require('path')

// 封装fs模块的读取文件操作
let read = (dirpath) => {
    console.log(dirpath)
    return new Promise((resolve, reject) => {
        fs.readFile(dirpath, 'utf-8', (err, data) => {
            if (err) {
                return reject(err)
            }
            resolve(data)
        })
    })
}
// 封装fs模块的读取文件夹操作
let readDir = (dirpath) => {
    return new Promise((resolve, reject) => {
        fs.readdir(dirpath, (err, files) => {
            if (err) {
                reject(err);
            } else {
                resolve(files);
            }
        });
    });
}
// 封装fs模块的写入文件操作
let write = (dirpath, data) => {
    return new Promise((resolve, reject) => {
        fs.writeFile(dirpath, data, (err) => {
            if (err) {
                return reject(err)
            }
            resolve({ message: '写入成功', code: 200 })
        })
    })
}


//追加文件内容
let addfile = (dirpath, data) => {
    return new Promise((resolve, reject) => {
        fs.appendFile(dirpath, data, (err) => {
            if (err) {
                return reject(err)
            }
            resolve({ message: 'ok', code: 200 })
        })
    }
    )
}


//删除文件
let delfile = (dirpath) => {
    return new Promise((resolve, reject) => {
        fs.unlink(dirpath, (err) => {
            if (err) {
                return reject(err)
            }
            resolve({ message: 'ok', code: 200 })
        })
    })
}



exports.read = read
exports.readDir = readDir
exports.write = write
exports.addfile = addfile
exports.delfile = delfile